package gui;

import entities.Medium;
import entities.Movie;
import implementation.CentralManagerImpl;
import implementation.MediumManagerImpl;
import implementation.MovieManagerImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import managers.CentralManager;
import managers.MediumManager;
import managers.MovieManager;
import models.MediumTableModel;
import models.MovieTableModel;

/**
 * @author Lucyia
 */
public class MainWindow extends javax.swing.JFrame {

    private MediumManager mediumMan = new MediumManagerImpl();
    private MovieManager movieMan = new MovieManagerImpl();
    private CentralManager centralMan = new CentralManagerImpl();
    //private int lastSelectedMediumIndex = -1;
    //private int lastSelectedMovieIndex = -1;
    
    private boolean searchFieldSelected = false;

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        utilities.DBUtils.openDBConnection();
        initComponents();
        refreshMediumTable();
        refreshMovieTable();

        SelectionListener listener = new SelectionListener(jTableMedia);
        jTableMedia.getSelectionModel().addListSelectionListener(listener);
        jTableMedia.getColumnModel().getSelectionModel().addListSelectionListener(listener);
        //setLocationRelativeTo(null); 


        //DAKY STARY ZAKOMENTOVANY KOD OD VLADA
        //System.out.println(movieMan.getAllMovies());
        /*
         * Movie movie = new Movie(); movie.setTitle("title"); movie.setCast(new
         * ArrayList<String>()); movie.setDirectors(new ArrayList<String>());
         * movie.setGenres(new ArrayList<Genre>());
         * movie.setCountriesOfOrigin(new ArrayList<String>());
         * movie.setReleaseYear(1989);
        movieMan.createMovie(movie);
         */

        /*
         * new SwingWorker<List<Movie>, Void>() { @Override protected
         * List<Movie> doInBackground() throws Exception { return
         * movieMan.getAllMovies(); } @Override protected void done() { try {
         * ((MovieTableModel)jTableFilms.getModel()).addMovies(get()); } catch
         * (InterruptedException | ExecutionException e) {
         * //logger.log(Level.WARNING, "swing worker exception", e); } };
        }.execute();
         */
        /*
         * List<Movie> movies=movieMan.getAllMovies(); for(Movie movie : movies)
         * { List<Medium> tmp =centralMan.getMediaWithMovie(movie);
         * movie.setMedium(tmp.isEmpty()?null:tmp.get(0)); }
        ((MovieTableModel)jTableFilms.getModel()).addMovies(movies);
         */


        //ODTIALTO VLADOV KOD
        /*
         * jTableFilms.getModel().addTableModelListener(new TableModelListener()
         * { @Override public void tableChanged(TableModelEvent e) { if
         * (e.getType() != TableModelEvent.UPDATE || e.getColumn() ==
         * TableModelEvent.ALL_COLUMNS) return;
         *
         * final Movie movie = ((MovieTableModel)
         * jTableFilms.getModel()).getMovieAt(e.getFirstRow()); if (movie !=
         * null) new SwingWorker<Void, Void>() { @Override protected Void
         * doInBackground() throws Exception { movieMan.updateMovie(movie);
         * return null; } }.execute(); } });
         *
         *
         *
         * new SwingWorker<List<Medium>, Void>() { @Override protected
         * List<Medium> doInBackground() throws Exception { return
         * mediumMan.getAllMedia(); } @Override protected void done() { try {
         * ((MediumTableModel)jTableMedia.getModel()).addMedia(get()); } catch
         * (InterruptedException | ExecutionException e) {
         * //logger.log(Level.WARNING, "swing worker exception", e); } };
         * }.execute(); System.out.println("here");
         * //((MediumList)tableMedia.getModel()).addMedia(mediumMan.getAllMedia());
         *
         *
         * jTableMedia.getSelectionModel().addListSelectionListener(new
         * ListSelectionListener() { @Override public void
         * valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting())
         * return;
         *
         * if (jTableMedia.getSelectedRow() != lastSelectedMediumIndex) { final
         * Medium med = ((MediumTableModel)
         * jTableMedia.getModel()).getMediumAt(jTableMedia.convertRowIndexToModel(jTableMedia.getSelectedRow()));
         * new SwingWorker<List<Movie>, Void>() { @Override protected
         * List<Movie> doInBackground() throws Exception { return
         * centralMan.getMoviesOnMedium(med); } @Override protected void done()
         * { try { ((MovieTableModel)jTableFilms.getModel()).addMovies(get()); }
         * catch (InterruptedException | ExecutionException e) {
         * //logger.log(Level.WARNING, "swing worker exception", e); } };
         * }.execute(); } } });
         *
         * jTableMedia.getModel().addTableModelListener(new TableModelListener()
         * { @Override public void tableChanged(TableModelEvent e) { if
         * (e.getType() != TableModelEvent.UPDATE || e.getColumn() ==
         * TableModelEvent.ALL_COLUMNS) return;
         *
         * final Medium medium = ((MediumTableModel)
         * jTableMedia.getModel()).getMediumAt(e.getFirstRow()); if (medium !=
         * null) new SwingWorker<Void, Void>() { @Override protected Void
         * doInBackground() throws Exception { mediumMan.updateMedium(medium);
         * return null; } }.execute(); } });
         *
         * setVisible(true);
         */
        //POTIALTO VLADOV KOD
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jInternalFrame1 = new javax.swing.JInternalFrame();
        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jTextFieldFilmSearch = new javax.swing.JTextField();
        jButtonSearch = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableFilms = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableMedia = new javax.swing.JTable();
        jButtonAddMedium = new javax.swing.JButton();
        jButtonDeleteMedium = new javax.swing.JButton();
        addMovieButton = new javax.swing.JButton();
        deleteMovieButton = new javax.swing.JButton();
        jLandedButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu6 = new javax.swing.JMenu();
        jMenu7 = new javax.swing.JMenu();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem7 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItemExit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenu5 = new javax.swing.JMenu();

        jInternalFrame1.setVisible(true);

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jMenuItem1.setText("jMenuItem1");

        jMenuItem4.setText("jMenuItem4");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextFieldFilmSearch.setText("Search for a film");
        jTextFieldFilmSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldFilmSearchMouseClicked(evt);
            }
        });
        jTextFieldFilmSearch.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFilmSearchFocusGained(evt);
            }
        });

        jButtonSearch.setText("Search");
        jButtonSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSearchActionPerformed(evt);
            }
        });

        jTableFilms.setModel(new MovieTableModel());
        jScrollPane2.setViewportView(jTableFilms);
        jTableFilms.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTableFilms.getColumnModel().getColumn(1).setPreferredWidth(40);
        jTableFilms.getColumnModel().getColumn(2).setPreferredWidth(17);
        jTableFilms.getColumnModel().getColumn(3).setPreferredWidth(17);
        jTableFilms.getColumnModel().getColumn(4).setPreferredWidth(7);
        jTableFilms.getColumnModel().getColumn(5).setPreferredWidth(30);
        jTableFilms.getColumnModel().getColumn(6).setPreferredWidth(30);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Medium list"));

        jTableMedia.setModel(new models.MediumTableModel());
        jTableMedia.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTableMedia);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButtonAddMedium.setText("Add new medium");
        jButtonAddMedium.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddMediumActionPerformed(evt);
            }
        });

        jButtonDeleteMedium.setText("Delete medium");
        jButtonDeleteMedium.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteMediumActionPerformed(evt);
            }
        });

        addMovieButton.setText("Add movie");
        addMovieButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addMovieButtonActionPerformed(evt);
            }
        });

        deleteMovieButton.setText("Delete selected movies");
        deleteMovieButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMovieButtonActionPerformed(evt);
            }
        });

        jLandedButton.setText("Land / Return");
        jLandedButton.setEnabled(false);
        jLandedButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jLandedButtonActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        jMenu6.setText("Add");
        jMenu1.add(jMenu6);

        jMenu7.setText("Remove");

        jMenuItem6.setText("Selected");
        jMenu7.add(jMenuItem6);

        jMenuItem7.setText("All");
        jMenu7.add(jMenuItem7);

        jMenu1.add(jMenu7);
        jMenu1.add(jSeparator1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText("Import");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem3.setText("Export");
        jMenu1.add(jMenuItem3);
        jMenu1.add(jSeparator2);

        jMenuItemExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItemExit.setText("Exit");
        jMenuItemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExitActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItemExit);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        jMenu5.setText("Help");
        jMenuBar1.add(jMenu5);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonAddMedium, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                    .addComponent(jButtonDeleteMedium, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLandedButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextFieldFilmSearch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 839, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(addMovieButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteMovieButton)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonAddMedium, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLandedButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldFilmSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonSearch))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonDeleteMedium, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addMovieButton)
                    .addComponent(deleteMovieButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSearchActionPerformed
        /*
         * if
         * (jTextFieldFilmSearch.getText().isEmpty()||jTextFieldFilmSearch.getText().equals("Search
         * for a film")) { new SwingWorker<List<Movie>,Void>() {
         *
         * @Override protected List<Movie> doInBackground() throws Exception {
         * return movieMan.getAllMovies(); }
         *
         * @Override protected void done(){ try {
         * ((MovieTableModel)jTableFilms.getModel()).addMovies(get()); } catch
         * (InterruptedException | ExecutionException e) {
         * //logger.log(Level.WARNING, "swing worker exception", e); } }
         *
         * }.execute(); return; }
         *
         * final String title = jTextFieldFilmSearch.getText().toLowerCase();
         *
         * new SwingWorker<List<Movie>,Void>() {
         *
         * @Override protected List<Movie> doInBackground() throws Exception {
         * List<Movie> tmp = movieMan.getAllMovies(); List<Movie> out = new
         * ArrayList<>();
         *
         * for(Movie movie : tmp) {
         * if(movie.getTitle().toLowerCase().indexOf(title)!=-1) out.add(movie);
         * }
         *
         * return out; }
         *
         * @Override protected void done(){ try {
         * ((MovieTableModel)jTableFilms.getModel()).addMovies(get()); } catch
         * (InterruptedException | ExecutionException e) {
         * //logger.log(Level.WARNING, "swing worker exception", e); } }
         *
         * }.execute();
         */
        //MOJ KOD ODTIALTO
    }//GEN-LAST:event_jButtonSearchActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExitActionPerformed
        //closes database connection
        utilities.DBUtils.closeDB();

        this.dispose();
    }//GEN-LAST:event_jMenuItemExitActionPerformed

    private void jButtonAddMediumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddMediumActionPerformed
        /*
         * NewMediumJDialog dialod = new NewMediumJDialog(this); final Medium
         * newMedium = dialod.showWindow(); if (newMedium != null) { new
         * SwingWorker<Void,Void>(){
         *
         * @Override protected Void doInBackground() throws Exception {
         * mediumMan.createMedium(newMedium); return null; }
         *
         * }.execute();
         *
         * ((MediumTableModel)jTableMedia.getModel()).addMedium(newMedium); }
         */

        NewMediumJDialog dialog = new NewMediumJDialog(this);
        dialog.setVisible(true);
    }//GEN-LAST:event_jButtonAddMediumActionPerformed

    private void jButtonDeleteMediumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteMediumActionPerformed
        /*
         * if (jTableMedia.getSelectedRowCount() == 0) {
         * JOptionPane.showMessageDialog(this, "No medium chosen.", "Attention",
         * 2); return; }
         *
         * String[] options = {"yes","no"}; if
         * (JOptionPane.showOptionDialog(this, "Do you really want to delete
         * chosen media?", "Are you sure?", JOptionPane.YES_NO_OPTION,
         * JOptionPane.QUESTION_MESSAGE,null, options, null) != 0) { return; }          *
         * Medium medium; final List<Medium> mediaToRemove = new
         * ArrayList<>(jTableMedia.getSelectedRowCount()); for (int i :
         * jTableMedia.getSelectedRows()) { medium = ((MediumTableModel)
         * jTableMedia.getModel()).getMediumAt(i); if (medium != null)
         * mediaToRemove.add(medium); }
         *
         * new SwingWorker<Void,Void>(){
         *
         * @Override protected Void doInBackground() throws Exception { for
         * (Medium medium : mediaToRemove) { mediumMan.deleteMedium(medium); }
         * return null; } }.execute();
         *
         * ((MediumTableModel) jTableMedia.getModel()).removeMedia(mediaToRemove);
         */

        //MOJ KOD
        if (jTableMedia.getSelectedRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No medium chosen.",
                    "Attention", 2);
            return;
        }

        String[] options = {"yes", "no"};
        if (JOptionPane.showOptionDialog(this, "Do you really want to delete chosen media?",
                "Are you sure?", JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, options, null) != 0) {
            return;
        }
        
        int index = jTableMedia.getSelectedRow();
        MediumTableModel model = (MediumTableModel) jTableMedia.getModel();
        Medium mediumToDelete = model.getMediumAt(index); 
        mediumMan.deleteMedium(mediumToDelete);
        model.removeMedium(mediumToDelete);
    }//GEN-LAST:event_jButtonDeleteMediumActionPerformed

    private void addMovieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addMovieButtonActionPerformed
        /*
         * if (jTableMedia.getSelectedRowCount() == 0) {
         * JOptionPane.showMessageDialog(this, "No medium chosen.", "Attention",
         * 2); return; }
         *
         * if (jTableMedia.getSelectedRowCount() > 1) {
         * JOptionPane.showMessageDialog(this, "More than one medium chosen.",
         * "Attention", 2); return; }
         *
         * final Medium medium=((MediumTableModel)
         * jTableMedia.getModel()).getMediumAt(jTableMedia.getSelectedRow());
         *
         *
         * NewMovieJDialog dialod = new NewMovieJDialog(this); final Movie
         * newMovie = dialod.showWindow(); newMovie.setMedium(medium); if
         * (newMovie != null) { new SwingWorker<Void,Void>(){
         *
         * @Override protected Void doInBackground() throws Exception {
         * movieMan.createMovie(newMovie); centralMan.putMovieOnMedium(newMovie,
         * medium); return null; }
         *
         * }.execute();
         *
         * ((MovieTableModel)jTableFilms.getModel()).addMovie(newMovie);
        }
         */
        
        //MOJ KOD
        if (jTableMedia.getSelectedRowCount() == 0) { 
            JOptionPane.showMessageDialog(this, "No medium chosen.", "Attention", 2);
        } else {
            NewMovieJDialog dialog = new NewMovieJDialog(this);
            
            dialog.setVisible(true);
        }
    }//GEN-LAST:event_addMovieButtonActionPerformed

    private void deleteMovieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMovieButtonActionPerformed
        /*
         * if (jTableFilms.getSelectedRowCount() == 0) {
         * JOptionPane.showMessageDialog(this, "No movie chosen.", "Attention",
         * 2); return; }
         *
         * String[] options = {"yes","no"}; if
         * (JOptionPane.showOptionDialog(this, "Do you really want to delete
         * chosen movies?", "Are you sure?", JOptionPane.YES_NO_OPTION,
         * JOptionPane.QUESTION_MESSAGE,null, options, null) != 0) { return; }          *
         * Movie movie; final List<Movie> moviesToRemove = new
         * ArrayList<>(jTableFilms.getSelectedRowCount()); for (int i :
         * jTableFilms.getSelectedRows()) { movie = ((MovieTableModel)
         * jTableFilms.getModel()).getMovieAt(i); if (movie != null)
         * moviesToRemove.add(movie); }
         *
         * new SwingWorker<Void,Void>(){
         *
         * @Override protected Void doInBackground() throws Exception { for
         * (Movie movie : moviesToRemove) {
         * centralMan.removeMovieFromMedium(movie, movie.getMedium());
         * movieMan.deleteMovie(movie); } return null; } }.execute();
         *
         * ((MovieTableModel) jTableFilms.getModel()).removeMovies(moviesToRemove);
         */
        
        //MOJ KOD
        int index = jTableFilms.getSelectedRow();
        if ( index == -1) { 
            JOptionPane.showMessageDialog(this, "No movie chosen.", "Attention", 2);
        } else {                        
            MovieTableModel model = (MovieTableModel) jTableFilms.getModel();
            Movie movieToDelete = model.getMovieAt(index);
            movieMan.deleteMovie(movieToDelete);
            model.removeMovie(movieToDelete);
        }
    }//GEN-LAST:event_deleteMovieButtonActionPerformed

    private void jLandedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLandedButtonActionPerformed
        int index = jTableMedia.getSelectedRow();

        System.out.println(index);

        if (index != -1) {
            MediumTableModel model = (MediumTableModel) jTableMedia.getModel();
            Medium medium = model.getMediumAt(index);
            medium.setLended(!medium.isLended());
            mediumMan.updateMedium(medium);
            model.fireTableRowsUpdated(index, index);
            setLandedButton(model.getMediumAt(index).isLended());
        }
    }//GEN-LAST:event_jLandedButtonActionPerformed

    private void jTextFieldFilmSearchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldFilmSearchMouseClicked
           //nothing to do here :)
    }//GEN-LAST:event_jTextFieldFilmSearchMouseClicked

    private void jTextFieldFilmSearchFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldFilmSearchFocusGained
        if (!searchFieldSelected) {
            jTextFieldFilmSearch.setText("");
            searchFieldSelected = true;
        }
    }//GEN-LAST:event_jTextFieldFilmSearchFocusGained

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addMovieButton;
    private javax.swing.JButton deleteMovieButton;
    private javax.swing.JButton jButtonAddMedium;
    private javax.swing.JButton jButtonDeleteMedium;
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JButton jLandedButton;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenu jMenu7;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem7;
    private javax.swing.JMenuItem jMenuItemExit;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JTable jTableFilms;
    private javax.swing.JTable jTableMedia;
    private javax.swing.JTextField jTextFieldFilmSearch;
    // End of variables declaration//GEN-END:variables

    public void setMediumToMovie(Movie movie) {
        int index = jTableMedia.getSelectedRow();
        if (index != -1) {
            MediumTableModel mediumModel = (MediumTableModel) jTableMedia.getModel();
            Medium currentMedium = (Medium) mediumModel.getMediumAt(index);
            //MovieTableModel movieModel = (MovieTableModel) jTableFilms.getModel();
            
            movie.setMedium(currentMedium);
            movieMan.updateMovie(movie);
            centralMan.putMovieOnMedium(movie, currentMedium);
            refreshMovieTable();
            System.out.println(currentMedium.getTitle());
            System.out.println(movie.getMedium());

        }
    }

    public void sentMediumToDB(Medium medium) {        
        mediumMan.createMedium(medium);
    }

    public void sentMovieToDB(Movie movie) {
        /*int index = jTableMedia.getSelectedRow();
        MediumTableModel mediumModel = (MediumTableModel) jTableMedia.getModel();
        Medium medium = (Medium) mediumModel.getMediumAt(index);
        movie.setMedium(medium);*/
        movieMan.createMovie(movie);
    }

    public void refreshMediumTable() {
        if (jTableMedia != null) {
            jTableMedia.removeAll();
            MediumTableModel model = (MediumTableModel) jTableMedia.getModel();
            List<Medium> allMediums = mediumMan.getAllMedia();
            model.addMedia(allMediums);
        }
    }

    public void refreshMovieTable() {
        if (jTableFilms != null) {            
            jTableFilms.removeAll();
            MovieTableModel model = (MovieTableModel) jTableFilms.getModel();
            List<Movie> allMovies = movieMan.getAllMovies();
            model.addMovies(allMovies);
        }
    }

    public void setLandedButton(boolean state) {
        if (state) {
            jLandedButton.setEnabled(true);
            jLandedButton.setText("Return to Library");
        } else {
            jLandedButton.setEnabled(true);
            jLandedButton.setText("Lend");
        }
    }
    
    public MovieManager getMovieMan() {
        return movieMan;
    }
    
public class SelectionListener implements ListSelectionListener {

        JTable table;
        int lastSelected = Integer.MAX_VALUE;

        SelectionListener(JTable table) {
            this.table = table;
        }

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // If cell selection is enabled, both row and column change events are fired
            if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) {
                int selection = this.table.getSelectedRow();
                if (lastSelected != selection) {
                    lastSelected = selection;
                    MediumTableModel model = (MediumTableModel) table.getModel();
                    System.out.println(model.getMediumAt(selection).toString());
                    setLandedButton(model.getMediumAt(selection).isLended());
                }
            }           
        }
    }
}
